package com.wwwarehouse.common.fragment;

import android.os.Bundle;
import android.support.annotation.Nullable;
import android.text.TextUtils;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.RelativeLayout;

import com.alibaba.android.arouter.facade.annotation.Route;
import com.alibaba.fastjson.JSON;
import com.github.lzyzsd.jsbridge.BridgeHandler;
import com.github.lzyzsd.jsbridge.BridgeWebView;
import com.github.lzyzsd.jsbridge.CallBackFunction;
import com.wwwarehouse.common.R;
import com.wwwarehouse.common.activity.BaseCardDeskActivity;
import com.wwwarehouse.common.activity.base.BaseFragment;
import com.wwwarehouse.common.bean.response.CommonClass;
import com.wwwarehouse.common.bean.response.NotificationDetailsResponseBean;
import com.wwwarehouse.common.bean.response.OperationDetailsResponseBean;
import com.wwwarehouse.common.constant.Constant;
import com.wwwarehouse.common.custom_widget.state_layout.StateLayout;
import com.wwwarehouse.common.eventbus_event.BackListenerEvent;
import com.wwwarehouse.common.eventbus_event.LogoutEvent;
import com.wwwarehouse.common.eventbus_event.MessageRouterEvent;
import com.wwwarehouse.common.http.NoHttpUtils;
import com.wwwarehouse.common.tools.AnimationUtils;
import com.wwwarehouse.common.tools.LogUtils;
import com.wwwarehouse.common.tools.ToastUtils;

import java.util.HashMap;
import java.util.Map;

import de.greenrobot.event.EventBus;

import static com.wwwarehouse.common.constant.Constant.sp_Token;

/**
 * JSBrige 封装通用WebView
 * Created by ShineF on 2017/9/23 0023.
 */
@Route(path = "/common/BridgeWebView")
public class CommonBridgeWebViewFragment extends BaseFragment implements View.OnClickListener {

    protected BridgeWebView mWebView = null;
    protected String mData;
    protected StateLayout mStateLayout;
    protected RelativeLayout mRlContent;
    protected RelativeLayout mRlOpposite;
    protected RelativeLayout mRlFront;
    protected BridgeWebView mOppositeWebView = null;
    protected ImageView mFlipView;
    private String oppositeUrl = null;
    protected RelativeLayout mRlComplaints;
    protected RelativeLayout mRlPrompt;
    protected RelativeLayout mRlCollection;

    private Button mGoBtn;

    private String mTitle = null;
    private String mOutsiteTitle = null;
    private boolean isOutsite = false;

    private NotificationDetailsResponseBean mNotificationDetailsResponseBean;

    private static final int REQUEST_GET_OPERATION_INFO = 0;

    @Nullable
    @Override
    public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        return inflater.inflate(R.layout.fragment_common_bridge_web_view, container, false);
    }

    @Override
    public void onActivityCreated(@Nullable Bundle savedInstanceState) {
        super.onActivityCreated(savedInstanceState);
        mWebView = $(R.id.bridge_web_view);
        mOppositeWebView = $(R.id.bridge_opposite_web_view);
        mStateLayout = $(R.id.sl_state);
        mFlipView = $(R.id.iv_flip);
        mRlContent = $(R.id.rl_content);
        mRlFront = $(R.id.rl_front);
        mRlOpposite = $(R.id.rl_opposite);
        mRlComplaints = $(R.id.rl_tucao);
        mRlPrompt = $(R.id.rl_tishi);
        mRlCollection = $(R.id.rl_shoucang);

        mGoBtn = $(R.id.btn_go);
    }

    @Override
    public void setTitle() {
        if (peekFragment() instanceof CommonBridgeWebViewFragment) {
            mActivity.setTitle(mTitle);
        }
    }

    @Override
    public void requestDatas() {
        EventBus.getDefault().register(this);
        mFlipView.setOnClickListener(this);
        mRlOpposite.setVisibility(View.GONE);
        mRlContent.setVisibility(View.INVISIBLE);
        mStateLayout.setVisibility(View.VISIBLE);
        mRlComplaints.setOnClickListener(this);
        mRlPrompt.setOnClickListener(this);
        mRlCollection.setOnClickListener(this);
        mStateLayout.showProgressView(true);

        Bundle bundle = getArguments();
        String url = bundle.getString("url");
        oppositeUrl = bundle.getString("oppositeUrl");

        if (TextUtils.isEmpty(oppositeUrl)) {
            mFlipView.setVisibility(View.GONE);
            ((BaseCardDeskActivity) mActivity).showRefreshBt();
            ((BaseCardDeskActivity) mActivity).hideScanFgBt();
        } else {
            mFlipView.setVisibility(View.VISIBLE);
            ((BaseCardDeskActivity) mActivity).hideRefreshBt();
            ((BaseCardDeskActivity) mActivity).showScanFgBt();
        }

        mData = bundle.getString("data");
        mTitle = bundle.getString("title");
        mOutsiteTitle = bundle.getString("outSiteTitle");
        mActivity.setTitle(mTitle);
        mWebView.loadUrl(url);
        registJsMethod();
        LogUtils.showErrLog("data----->" + mData);
    }

    private void registJsMethod() {
        mWebView.setDefaultHandler(new BridgeHandler() {
            @Override
            public void handler(String data, CallBackFunction function) {
                function.onCallBack(mData);
            }
        });

        //显示progressDialog
        mWebView.registerHandler("showProgress", new BridgeHandler() {
            @Override
            public void handler(String data, CallBackFunction function) {
//                showProgressDialog("正在加载");
            }
        });

        //隐藏StateLayout和ProgressDialog
        mWebView.registerHandler("hideProgress", new BridgeHandler() {
            @Override
            public void handler(String data, CallBackFunction function) {
                if (mRlContent.getVisibility() != View.VISIBLE) {
                    mRlContent.setVisibility(View.VISIBLE);
                }
                if (mStateLayout.getVisibility() != View.INVISIBLE) {
                    mStateLayout.setVisibility(View.INVISIBLE);
                    mStateLayout.showContentView();
                }
                dismissProgressDialog();
            }
        });

        //跳转到登录页
        mWebView.registerHandler("gotoLogin", new BridgeHandler() {
            @Override
            public void handler(String data, CallBackFunction function) {
                EventBus.getDefault().post(new LogoutEvent("logout"));
            }
        });

        //获取请求错误信息
        mWebView.registerHandler("showErrorMsg", new BridgeHandler() {
            @Override
            public void handler(String data, CallBackFunction function) {
                mRlContent.setVisibility(View.INVISIBLE);
                mStateLayout.setVisibility(View.VISIBLE);
                mStateLayout.showSystemView(data, true);
                mStateLayout.setSystemListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        mWebView.reload();
                    }
                });
                LogUtils.showErrLog("showErrorMsg");
            }
        });
        //数据为空的界面
        mWebView.registerHandler("dataEmptyOperation", new BridgeHandler() {
            @Override
            public void handler(String data, CallBackFunction function) {
                mRlContent.setVisibility(View.INVISIBLE);
                mStateLayout.setVisibility(View.VISIBLE);
                mStateLayout.showEmptyView(data, true);
                mStateLayout.setEmptyListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        mWebView.reload();
                    }
                });
                LogUtils.showErrLog("showEmptyView");
            }
        });

        //Js获取请求的参数
        mWebView.callHandler("getData", mData, new CallBackFunction() {
            @Override
            public void onCallBack(String data) {
                ToastUtils.showToast(data);
            }
        });

        mWebView.callHandler("getToken", sp.getValue(sp_Token), new CallBackFunction() {
            @Override
            public void onCallBack(String data) {

            }
        });

        // TODO: 2017/9/23 0023 根据需求不同去添加与前端约束好的方法
        mWebView.registerHandler("reponseOrdersMonitorClick", new BridgeHandler() {
            @Override
            public void handler(String data, CallBackFunction function) {
                pushFragment("/contract/ImportOrdersMonitorPagerFragment", null);
            }
        });

        // 消息中心，消息详情
        mWebView.registerHandler("responseMessageDetails", new BridgeHandler() {
            @Override
            public void handler(String data, CallBackFunction function) {
                mNotificationDetailsResponseBean = JSON.parseObject(data, NotificationDetailsResponseBean.class);

                if ("0".equals(mNotificationDetailsResponseBean.getData().getCode())) {
                    if ("task_notice".equals(mNotificationDetailsResponseBean.getData().getData().getMessageType())) {
                        // 任务类型，显示按钮 查询任务状态
                        getOperationInfo(mNotificationDetailsResponseBean.getData().getData().getFeature().getCardUkid());
                    } else {
                        // 非任务类型，隐藏按钮
                        mGoBtn.setVisibility(View.GONE);
                    }
                } else {
                    toast(mNotificationDetailsResponseBean.getData().getMsg());
                }
            }
        });
    }

    @Override
    public void refreshClick() {
        mWebView.callHandler("getToken", sp.getValue(sp_Token), new CallBackFunction() {
            @Override
            public void onCallBack(String data) {

            }
        });
    }

    @Override
    public void onClick(View view) {
        if (R.id.iv_flip == view.getId()) {
            AnimationUtils.cardTransAnims(mRlContent, mRlFront, mRlOpposite, null);
            if (!TextUtils.isEmpty(oppositeUrl)) {
                mOppositeWebView.loadUrl(oppositeUrl);
            }
            isOutsite = !isOutsite;
            if (isOutsite) {
                mActivity.setTitle(mOutsiteTitle);

            } else {
                mActivity.setTitle(mTitle);
            }
        } else if (R.id.rl_tucao == view.getId()) {
            ToastUtils.showToast("吐槽");
        } else if (R.id.rl_tishi == view.getId()) {
            ToastUtils.showToast("提示");
        } else if (R.id.rl_shoucang == view.getId()) {
            ToastUtils.showToast("收藏");
        }
    }

    public void onEventMainThread(BackListenerEvent event) {
        if (peekFragment() instanceof CommonBridgeWebViewFragment && "CommonBridgeWebViewFragment".equals(event.getMsg())) {
            if (TextUtils.isEmpty(oppositeUrl)) {
                popFragment();
            } else {
                ((BaseCardDeskActivity) mActivity).cleanBackStack();
            }
        }
    }

    NoHttpUtils.OnResponseListener mOnResponseListener = new NoHttpUtils.OnResponseListener() {
        @Override
        public void onSucceed(CommonClass commonClass, int what) {
            switch (what) {
                case REQUEST_GET_OPERATION_INFO:
                    if ("0".equals(commonClass.getCode())) {
                        OperationDetailsResponseBean operationDetailsResponseBean = JSON.parseObject(commonClass.getData().toString(), OperationDetailsResponseBean.class);

                        mGoBtn.setVisibility(View.VISIBLE);

                        //状态：0 初始（未处理） 5 执行中 8 暂停 10 已完成 15 已取消
                        if ("10".equals(operationDetailsResponseBean.getStatus()) ||
                                "15".equals(operationDetailsResponseBean.getStatus())) {
                            mGoBtn.setEnabled(false);
                            mGoBtn.setText(operationDetailsResponseBean.getOperationName() + getString(R.string.invalidate));
                        } else {
                            mGoBtn.setEnabled(true);
                            mGoBtn.setText(getString(R.string.go) + operationDetailsResponseBean.getOperationName());

                            mGoBtn.setOnClickListener(new View.OnClickListener() {
                                @Override
                                public void onClick(View v) {
                                    // 发送通知，通知跳转到哪个界面
                                    EventBus.getDefault().post(new MessageRouterEvent(mNotificationDetailsResponseBean));
                                }
                            });
                        }
                    } else {
                        mGoBtn.setVisibility(View.GONE);
                    }
                    break;
                default:
                    break;
            }
        }

        @Override
        public void onFailed(String result, int what) {
            mGoBtn.setVisibility(View.GONE);
        }

        @Override
        public void onFinish(int what) {

        }
    };

    /**
     * 获取任务状态
     * @param operationUkid
     */
    private void getOperationInfo(String operationUkid) {
        Map map = new HashMap();

        map.put("operationUkid", operationUkid);

        NoHttpUtils.httpPost(Constant.URL_GET_OPERATION_INFO, map, mOnResponseListener, REQUEST_GET_OPERATION_INFO);
    }
}
